﻿using Autofac;
using Biotech.Log;
using project.B12.application.Ioc;
using project.B12.application.ViewModels.Dialogs;
using project.B12.IService;
using project.B12.Service;
using project.B12.Service.UserService;
using project.B12.Views.Dialog;
using project.B8.Models;
using software.Common.MVVM;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace project.B12.ViewModels
{
    public class LoginViewModel : ObservableObject
    {
        Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
        #region Service
        public IUserService userService { get; set; }//用户服务

        public IServiceDevice serviceDevice { get; set; }
        #endregion

        #region Command
        public RelayCommand LoginCommand => new(Login);//登录按钮命令
        public RelayCommand LoginCloseCommand => new(LoginClose);//登录取消按钮命令
        #endregion

        #region Model
        public LoginInfo loginInfo { get; set; }//登录信息model
        private string messagesTips; //登录消息提示
        private Visibility _showProgress = Visibility.Collapsed;// 登录等待动画可视性
        private bool buttonIsEnabled = true;//登录按钮可用性
        public string? lastLoginName = string.Empty;//最后一次成功登陆的用户名
        public bool IsLogOut { get; set; }
        public string MessagesTips
        {
            get { return messagesTips; }
            set { messagesTips = value; this.RaisePropertyChanged(); }
        }
        public Visibility ShowProgress
        {
            get { return _showProgress; }
            set { _showProgress = value; this.RaisePropertyChanged(); }
        }
        public bool ButtonIsEnabled
        {
            get { return buttonIsEnabled; }
            set { buttonIsEnabled = value; this.RaisePropertyChanged(); }
        }
        public string? LastLoginName
        {
            get { return lastLoginName; }
            set { lastLoginName = value; this.RaisePropertyChanged(); }
        }

        #endregion

        public LoginViewModel(IUserService _userService, IServiceDevice _serviceDevice)
        {
            userService = _userService;
            serviceDevice = _serviceDevice;
            loginInfo = new LoginInfo(userService.GetConfigUserName());
        }

        /// <summary>
        /// 系统登录
        /// </summary>
        /// <param name="parameter"></param>
        private async void Login()
        {
            try
            {
                ButtonIsEnabled = false;
                this.ShowProgress = Visibility.Visible;//暂时封闭按钮屏蔽重复登陆命令
                await Task.Run(() =>
                {
                    try
                    {
                        var result = userService.Login(loginInfo.UserName, loginInfo.Password, true);//登陆验证
                        if (result.Success)
                        {
                            try
                            {
                                if (!serviceDevice.Connect())
                                {
                                    dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        WPF.Controls.Message.Push($"通讯连接失败", MessageBoxImage.Error);
                                    }));
                                }

                            }
                            catch
                            {
                                dispatcher.BeginInvoke(new Action(() =>
                                {
                                    WPF.Controls.Message.Push($"通讯连接失败", MessageBoxImage.Error);
                                }));
                            }
                            

                            LoggerFactory.Instance.CurrentLogger.LogInfo($"登录系统\n①用户名：({userService.CurrentUser.Name})\n②角色名：({userService.CurrentUser.RoleName})", "", "用户");
                            this.MessagesTips = String.Empty;//提示消息清空
                            loginInfo.Password = String.Empty;//密码内容清空
                            if (string.IsNullOrEmpty(LastLoginName))
                                ViewModelLocator.MainWindowViewModel.ChangeToMainView(true);//(首次登录)调用主框架方法切回主界面
                            else if (!string.IsNullOrEmpty(LastLoginName) && LastLoginName == loginInfo.UserName)
                                ViewModelLocator.MainWindowViewModel.ChangeToMainView(false);//(重复登录)调用主框架方法切回主界面
                            else if (!string.IsNullOrEmpty(LastLoginName) && LastLoginName != loginInfo.UserName)
                                ViewModelLocator.MainWindowViewModel.ChangeToMainView(true);//(新用户登录)调用主框架方法切回主界面
                            
                            LastLoginName = loginInfo.UserName;

                            //serviceDevice.Refresh();
                            serviceDevice.Refresh();
                            if (!IsLogOut && serviceDevice.isConnect)
                            {
                                serviceDevice.InitItems64();
                                serviceDevice.Start();
                            }
                            else if (!IsLogOut)
                                serviceDevice.InitItems64();
                        }
                        else
                        {
                            this.MessagesTips = result.Message;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.MessagesTips = ex.Message;
                    }
                    finally
                    {
                        this.ShowProgress = Visibility.Collapsed;
                        ButtonIsEnabled = true;
                    }
                });
            }
            catch (Exception ex)
            {
                this.MessagesTips = ex.Message;
            }
        }



        /// <summary>
        /// 登录界面关闭
        /// </summary>
        /// <param name="obj"></param>
        private async void LoginClose()
        {
            try
            {
                if (await MessageDialogView.ComfirmMessage("退出登录", $"请确认是否退出登录？", "RootLogin"))
                {
                    LoggerFactory.Instance.CurrentLogger.LogInfo("登录界面软件关闭", "", "软件");
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                this.MessagesTips = $"错误信息：{ex}";
            }
        }
    }
}
